import os
import subprocess
import jieba
import hashlib
import time
from datetime import datetime
import re
from tool import storage
from pathlib import Path

CollectConfigKey = "CollectConfigKey"
MainConfigKey = "MainConfigKey"

def isNotEmpty(o):
    return isEmpty(o) == False

def isEmpty(o):
    if o == None:
        return True
    if len(o) == 0:
        return True
    return False

    
# 终端执行命令
def terminal(command):
    if command == None:
        return "执行命令为空"
    print(command)
    # reply = subprocess.check_output(command)
    # return reply.decode('utf-8')
    return subprocess_check_output(command)


def subprocess_check_output(*args):
    p = subprocess.Popen(*args, shell=True, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    msg = ''
    for line in p.stdout.readlines():
        msg += line.decode()
    status = p.wait()
    return msg

# 分词 数组
def participle_list(str):
    if str == None or len(str) == 0:
        return []
    # 自定义分词
    jieba.load_userdict('Source/userdict.txt')
    seg_list = jieba.cut(str)  # 默认是精确模式
    res_list = []
    # todo 删除一个词的
    for seg in seg_list:
        if len(seg) > 1:
            # TODO 特殊处理 徐老师来巡山
            if seg.find(u'徐老师来巡山') != -1:
                res_list.append('英雄联盟')
            res_list.append(seg)
    return res_list

# 分词 字符串,逗号分开
def participle_str(str):
    res_list = participle_list(str)
    if res_list != None and len(res_list) > 0:
        return ','.join(res_list)
    return ""


# 完整url
def getCompleteUrl(url):
    if url.startswith('http'):
        url = url
    elif url.startswith('//'):
        url = 'https:' + url
    elif url.startswith('/'):
        url = 'https:/' + url
    else:
        url = 'https://' + url
    return url


def getImageSize(width, height):
    # 160 90
    if width > height:
        return (160, 90)
    return (90*(9/16), 90)

def md5(string):
    return hashlib.md5(string.encode('utf-8')).hexdigest()[8:-8]


def timestamp(stamp):
    timeArray = time.localtime(stamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return otherStyleTime


def beforeHours2Date(hours, date_format='%Y-%m-%d %H:%M:%S'):
    hours = int(hours)
    t = time.time() - hours*60*60
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
    return t


def beforeHours2Date1(hours, date_format='%Y-%m-%d %H:%M:%S'):
    hours = int(hours)
    t = time.time() - hours*60*60
    t = time.strftime('%Y-%m-%d', time.localtime(t))
    return t


def parse_ymd(s):
    if s == None or len(s) == 0:
        return None
    s = s.replace('年', '-').replace('月', '-').replace('日', '')

    aa = re.findall(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})", s)

    if aa != []:
        a = aa[0]

    else:
        if '月' in s:
            s = s.replace('月', '-').replace('日', '')
            mon_s, day_s = s.split('-')
            year_s = '2021'
            a = datetime(int(year_s), int(mon_s), int(day_s))
            a = a.strftime('%Y-%m-%d %H:%M:%S')

        long = re.findall('(-)', s)
        if len(long) == 2:
            year_s, mon_s, day_s = s.split('-')
            a = datetime(int(year_s), int(mon_s), int(day_s))
            a = a.strftime('%Y-%m-%d %H:%M:%S')

        if len(long) == 1:
            mon_s, day_s = s.split('-')
            year_s = '2021'
            a = datetime(int(year_s), int(mon_s), int(day_s))
            a = a.strftime('%Y-%m-%d %H:%M:%S')
        else:
            if '前天' in s:
                a = 3
                a = beforeHours2Date(a, date_format='%Y-%m-%d %H:%M:%S')

            if '天前' in s:
                a = re.findall('(.*?)天前', s)
                a = beforeHours2Date(a[0], date_format='%Y-%m-%d %H:%M:%S')

            if '周前' in s:
                a = 7
                a = beforeHours2Date(a, date_format='%Y-%m-%d %H:%M:%S')

            if '小时前' in s:
                a = re.findall('(.*?)小时前', s)
                a = beforeHours2Date(a[0], date_format='%Y-%m-%d %H:%M:%S')

            if '昨天' in s:
                a = 24
                b = re.findall('昨天(.*)', s)
                a = beforeHours2Date1(a, date_format='%Y-%m-%d %H:%M:%S')
                a = a+' '+b[0]+':00'

            if '秒' in s:
                a = 0
                a = beforeHours2Date(a, date_format='%Y-%m-%d %H:%M:%S')

            if '分钟前' in s:
                a = 0.5
                a = beforeHours2Date(a, date_format='%Y-%m-%d %H:%M:%S')

            if '刚刚' in s:
                a = 0
                a = beforeHours2Date(a, date_format='%Y-%m-%d %H:%M:%S')

    return a

# 查询关联数组
def relation_keyword(text):
    if text == '王者荣耀':
        return ["王者"]
    elif text == '英雄联盟':
        return ["英雄联盟", "LOL"]
    elif text == '吃鸡':
        return ["吃鸡", "绝地求生", "和平精英", "刺激战场"]
    return [text]

def get_collect_config():
    configDic = storage.getValue(CollectConfigKey)
    if configDic == None:
        configDic = {
            "keyword": "王者荣耀,英雄联盟,LOL,吃鸡,绝地求生,和平精英,刺激战场,搞笑,动漫",
            "page": "3",
            "creatorPage": "1",
            "creatorTime": "0"
        }
    return configDic

def set_collect_config(dic):
    storage.store(CollectConfigKey, dic)


def get_main_config():
    configDic = storage.getValue(MainConfigKey)
    return configDic

def set_main_config(dic):
    storage.store(MainConfigKey, dic)




